package cn.donting.web.desktop.core;


import cn.donting.web.desktop.core.entity.AppInfo;
import cn.donting.web.desktop.core.exception.AppException;
import cn.donting.web.desktop.core.loader.AppURLClassLoader;
import cn.donting.web.desktop.top.App;
import cn.donting.web.desktop.top.AppContext;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author donting
 * 2021-05-30 下午2:59
 */
@Slf4j
@Getter
public abstract class Application {
    public static Long sysAppId = 0L;

    protected final AppURLClassLoader appClassLoader;
    protected AppContext appContext;
    protected App app;
    protected Class<?> mainClass;
    protected AppInfo appInfo;

    public Application(AppURLClassLoader appClassLoader, App app, Class<?> mainClass) {
        this.appClassLoader = appClassLoader;
        this.app = app;
        this.mainClass = mainClass;
    }

    public long getId() {
        return appInfo.getAppId();
    }

    public abstract AppContext run() throws Exception;

    public abstract int stop() throws Exception;

    public void setAppInfo(AppInfo appInfo) {
        if (this.appInfo != null) {
            log.warn("appInfo is set");
            return;
        }
        this.appInfo = appInfo;
    }

    public String getAppKey() throws Exception {
        URL resource = appClassLoader.getResource("META-INF/wapKey.key");
        if (resource == null) {
            throw new AppException(appInfo.getName() + "缺失 META-INF/wapKey.key");
        }

        InputStream inputStream = resource.openStream();

        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        String key = new String(bytes, StandardCharsets.UTF_8);
        return key;
    }
}
